import { useState } from 'react'
import { getData2 } from '../Data'
import { useMount, useReactive } from 'ahooks'

import { isNumber, saveFile } from "@grapecity/wijmo"
import { FlexGrid } from "@grapecity/wijmo.react.grid"
import { CellRange } from "@grapecity/wijmo.grid";

import { Button } from 'antd'

const WijmoG02 = () => {

    const InitData = useReactive({
        init: null,
        tally: { cnt: 0, cntAll: 1, sum: 0, avg: 0 }
    })


    const [Data, setData] = useState()
    useMount(() => { setData(getData2(100)) })


    const onSelect = () => {
        const tally = { cnt: 0, cntAll: 0, sum: 0, avg: 0 }, ranges = InitData.init.selectedRanges
        ranges.forEach((_, i) => { aggregateRange(tally, InitData.init, ranges, i) })
        InitData.tally = tally
    }

    const aggregateRange = (tally, grid, ranges, index) => {
        let rng = ranges[index];
        const topRow = rng.topRow;
        const bottomRow = rng.bottomRow;
        const leftCol = rng.leftCol;
        const rightCol = rng.rightCol;
        for (let r = topRow; r <= bottomRow; r++) {
            for (let c = leftCol; c <= rightCol; c++) {
                let overlapped = false
                for (let i = 0; i < index && !overlapped; i++) {
                    const prevRng = ranges[i]
                    if (prevRng.contains(r, c)) overlapped = true
                }
                if (!overlapped) {
                    let data = grid.getCellData(r, c, false)
                    if (isNumber(data)) {
                        tally.cnt++
                        tally.sum += data
                    }
                    if (data !== '' && data !== null) tally.cntAll++
                }
            }
        }
        tally.avg = tally.cnt > 0 ? tally.sum / tally.cnt : 0;
    }


    const onSave = (state) => {
        const init = InitData.init
        let rng = state ? null : new CellRange(0, 0, init.rows.length - 1, init.columns.length - 1)
        console.log(state, init.getClipString(rng, true, true))
        // saveFile(init.getClipString(rng, true, true), state ? '选中数据.csv' : '全部数据.csv');
    }


    if (Data) {
        return (
            <div className="Page">
                <FlexGrid
                    alternatingRowStep={0}
                    showMarquee={true}
                    anchorCursor={true}
                    selectionMode="MultiRange"
                    showSelectedHeaders="All"
                    itemsSource={Data}
                    initialized={s => InitData.init = s}
                    selectionChanged={onSelect}
                />
                <div>{JSON.stringify(InitData.tally)}</div>
                <Button onClick={() => onSave(false)}>保存全部</Button>
                <Button onClick={() => onSave(true)}>保存选中</Button>
            </div>
        )
    }
};

export default WijmoG02